package com.emm.yixun.system.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.model.enums.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.jpush.api.utils.StringUtils;

import com.emm.yixun.basic.service.BaseCodeTypeService;
import com.emm.yixun.basic.service.BaseCodeValueService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.BaseDataReqDto;
import com.emm.yixun.common.app.ProjectsPmoResDto;
import com.emm.yixun.common.exception.BusinessException;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.BaseCodeType;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.BaseCodeValueInfo;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BaseCodeTypeDto;
import com.emm.yixun.common.model.dto.BaseCodeValueDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.EnumUtil;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;

@Service("baseCodeValueServiceFacade")
@WebService(name = "com.emm.yixun.system.service.BaseCodeValueServiceFacade")
public class BaseCodeValueServiceFacadeImpl implements BaseCodeValueServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private BaseCodeValueService service;

	@Autowired
	private BaseCodeTypeService baseCodeTypeService;

	@Autowired
	private UserService userService;

	@Override
	public Response<BaseCodeValueDto> save(BaseCodeValueDto dto) {
		Response<BaseCodeValueDto> response = new Response<BaseCodeValueDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			BaseCodeValueDto mDto = service.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(BaseCodeValueDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			BaseCodeValueDto mDto = new BaseCodeValueDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<BaseCodeValue> findById(Long id) {
		Response<BaseCodeValue> response = new Response<BaseCodeValue>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			BaseCodeValue entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<BaseCodeValue> findByDto(BaseCodeValueDto dto) {
		ResponseList<BaseCodeValue> response = new ResponseList<BaseCodeValue>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<BaseCodeValue> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<BaseCodeValue> findPageByDto(BaseCodeValueDto dto, Integer begin, Integer row) {
		Page<BaseCodeValue> response = new Page<BaseCodeValue>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<BaseCodeValue> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<BaseCodeValueDto> findListByTypeName(BaseCodeValueDto dto) {
		ResponseList<BaseCodeValueDto> response = new ResponseList<BaseCodeValueDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<BaseCodeValueDto> list = service.selectListByTypeName(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<BaseCodeValue> selectListFilterDelFlag(BaseCodeValueDto dto) {
		ResponseList<BaseCodeValue> response = new ResponseList<BaseCodeValue>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<BaseCodeValue> list = service.selectListFilterDelFlag(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public boolean baseCodeValueInit(User user, ProjectDto dto, String[] codeTypeArr, String[] codeTypeArr2,
			String[][] codeValueArrs, String codeType) {
		boolean flag = true;
		try {
			for (int ii = 0; ii < codeTypeArr.length; ii++) {
				String typeName = codeTypeArr[ii];
				// 创建类型
				BaseCodeTypeDto bctDto = new BaseCodeTypeDto();
				bctDto.setCodeType(codeType);
				bctDto.setTypeName(typeName);
				bctDto.setTypeValue(codeTypeArr2[ii]);
				bctDto.setSort(String.valueOf(ii + 1));
				bctDto.setRemark("初始化");
				bctDto.setMerchantId(user.getMerchantId());
				bctDto.setProjectId(dto.getId());
				bctDto.setCreateUserId(user.getId());
				bctDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				bctDto = baseCodeTypeService.create(bctDto);
				String[] codeValueArr = codeValueArrs[ii];
				for (int jj = 0; jj < codeValueArr.length; jj++) {
					String codeValue = codeValueArr[jj];
					BaseCodeValueDto bcvDto = new BaseCodeValueDto();
					bcvDto.setTypeId(bctDto.getId());
					bcvDto.setCodeName(codeValue);
					bcvDto.setCodeValue(codeValue);
					bcvDto.setSort(String.valueOf(jj + 1));
					bcvDto.setRemark("初始化");
					bcvDto.setMerchantId(user.getMerchantId());
					bcvDto.setProjectId(dto.getId());
					bcvDto.setCreateUserId(user.getId());
					bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					service.create(bcvDto);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

	@Override
	public ProjectsPmoResDto baseline(List<BaseDataReqDto> baseDataReqDtos, String interfaceName) {
		ProjectsPmoResDto resDto = new ProjectsPmoResDto();
		List<BaseDataReqDto> rootList = new ArrayList<BaseDataReqDto>();
		List<BaseDataReqDto> baseValueList = new ArrayList<BaseDataReqDto>();
		try {
			for (BaseDataReqDto basedata : baseDataReqDtos) {
				if (basedata.getParent().equals("root")) {
					rootList.add(basedata);
				} else {
					baseValueList.add(basedata);
				}
			}
			BaseCodeTypeDto codeTypeEntity = new BaseCodeTypeDto();
			codeTypeEntity.setCodeType(CodeTypeEnum.CUSTOMER_02.getNo());
			codeTypeEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<BaseCodeType> actualRootList = baseCodeTypeService.selectListByDto(codeTypeEntity);
			if (actualRootList == null) {
				actualRootList = new ArrayList<BaseCodeType>();
			}
			UserDto userDto = new UserDto();
			userDto.setIsAdmin("1");
			// 绿城专属
			userDto.setMerchantId(Long.valueOf(MerchantEnum.GREEN_TOWN.getNo()));
			userDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			User user = userService.selectByDto(userDto);
			boolean flag = true;
			if ("baseline".equals(interfaceName)) {
				if (actualRootList.size() <= rootList.size()) {
					saveOrUpdate(rootList, user);
				} else {
					resDto.setCode("10000005");
					resDto.setDesc("非法参数");
					return resDto;
				}
			} else {
				saveOrUpdate(rootList, user);
				flag = false;
			}

			// 得到所有的二级业态
			List<BaseCodeValue> compareBaseCodeList = service.selectListByBaseType(null);

			// 二级业态处理
			for (BaseDataReqDto baseCodeValue : baseValueList) {
				BaseCodeTypeDto vaildBaseCode = new BaseCodeTypeDto();
				vaildBaseCode.setCodeType(CodeTypeEnum.CUSTOMER_02.getNo());
				vaildBaseCode.setTypeValue(baseCodeValue.getParent());
				vaildBaseCode.setDelFlag(DelFlagEnum.UNDEL.getNo());
				BaseCodeType codeType = baseCodeTypeService.selectByDto(vaildBaseCode);
				if (codeType == null) {
					resDto.setCode("10000005");
					resDto.setDesc("不存在" + baseCodeValue.getName() + "上级业态");
					return resDto;
				} else {
					BaseCodeValue systemResult = vaildIsTrue(compareBaseCodeList, baseCodeValue);
					if (systemResult != null) { // 在当前系统中存在当前业态值，更新
						systemResult.setCodeName(baseCodeValue.getName());
						if (StringUtils.isNotEmpty(baseCodeValue.getEffectiveTime())) {
							systemResult.setEffectiveTime(DateUtils.StringToDate(baseCodeValue.getEffectiveTime()));
						}
						if (StringUtils.isNotEmpty(baseCodeValue.getExpiredTime())) {
							systemResult.setExpiredTime(DateUtils.StringToDate(baseCodeValue.getExpiredTime()));
						}
						BaseCodeValueDto dto = new BaseCodeValueDto();
						BeanUtil.convert2T(dto, systemResult);
						service.update(dto);
					} else {
						// 新增
						BaseCodeValueDto addDto = new BaseCodeValueDto();
						addDto.setTypeId(codeType.getId());
						addDto.setCodeName(baseCodeValue.getName());
						addDto.setCodeValue(baseCodeValue.getId());
						addDto.setRemark("接口同步");
						addDto.setMerchantId(user.getMerchantId());
						addDto.setCreateTime(new Date());
						addDto.setCreateUserId(user.getId());
						if (StringUtils.isNotEmpty(baseCodeValue.getEffectiveTime())) {
							addDto.setEffectiveTime(DateUtils.StringToDate(baseCodeValue.getEffectiveTime()));
						}
						if (StringUtils.isNotEmpty(baseCodeValue.getExpiredTime())) {
							addDto.setExpiredTime(DateUtils.StringToDate(baseCodeValue.getExpiredTime()));
						}
						addDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
						service.create(addDto);
					}
				}
			}
			// 将没有进行处理的数据，失效时间都改成调用接口时间的前一天
			if (flag) {
				if (compareBaseCodeList != null && compareBaseCodeList.size() > 0) {
					for (BaseCodeValue baseVal : compareBaseCodeList) {
						baseVal.setExpiredTime(DateUtils.getPreDate(new Date(), 1));
						baseVal.setDelFlag(DelFlagEnum.UNDEL.getNo());
						BaseCodeValueDto updateDto = new BaseCodeValueDto();
						BeanUtil.convert2T(updateDto, baseVal);
						service.update(updateDto);

					}
				}
			}
			resDto.setCode("00000000");
			resDto.setDesc("调用成功");
			return resDto;

		} catch (BusinessException e) {
			resDto.setCode("00000006");
			resDto.setDesc("日期转换错误");
		} catch (Exception e) {
			resDto.setCode("00000005");
			resDto.setDesc("数据库操作异常");
			logger.error("baseline error: ", e);
		}
		return resDto;
	}

	public BaseCodeValue vaildIsTrue(List<BaseCodeValue> compareBaseCodeList, BaseDataReqDto baseCodeValue) {
		if (compareBaseCodeList != null && compareBaseCodeList.size() > 0) {
			BaseCodeValue code = new BaseCodeValue();
			for (BaseCodeValue list : compareBaseCodeList) {
				if (list.getCodeValue().equals(baseCodeValue.getId())) {
					code = list;
					compareBaseCodeList.remove(list);
					return code;
				}
			}
		}
		return null;
	}

	public void saveOrUpdate(List<BaseDataReqDto> rootList, User user) throws BusinessException {
		for (BaseDataReqDto reqRoot : rootList) {
			BaseCodeTypeDto queryEntity = new BaseCodeTypeDto();
			queryEntity.setCodeType(CodeTypeEnum.CUSTOMER_02.getNo());
			queryEntity.setTypeValue(reqRoot.getId());
			/* queryEntity.setTypeName(reqRoot.getName()); */
			/* queryEntity.setTypeValue(reqRoot.getParent()); */
			BaseCodeTypeDto baseCodeEntity = new BaseCodeTypeDto();
			baseCodeEntity.setCodeType(CodeTypeEnum.CUSTOMER_02.getNo());
			baseCodeEntity.setTypeName(reqRoot.getName());
			baseCodeEntity.setTypeValue(reqRoot.getId());
			baseCodeEntity.setRemark("接口同步");
			baseCodeEntity.setMerchantId(user.getMerchantId());
			baseCodeEntity.setCreateUserId(user.getId());
			baseCodeEntity.setCreateTime(new Date());
			if (StringUtils.isNotEmpty(reqRoot.getEffectiveTime())) {
				Date effeiteTime = DateUtils.StringToDate(reqRoot.getEffectiveTime());
				baseCodeEntity.setEffectiveTime(effeiteTime);
			}
			if (StringUtils.isNotEmpty(reqRoot.getExpiredTime())) {
				Date expiredTime = DateUtils.StringToDate(reqRoot.getExpiredTime());
				if (expiredTime == null) {
					throw new BusinessException("00000006", "日期转换错误");
				}
				baseCodeEntity.setExpiredTime(expiredTime);
			}
			baseCodeEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<BaseCodeType> queryResult = baseCodeTypeService.selectListByDto(queryEntity);
			if (queryResult == null || queryResult.size() <= 0) {
				baseCodeTypeService.create(baseCodeEntity);
			} else {
				baseCodeEntity.setId(queryResult.get(0).getId());
				baseCodeEntity.setUpdateTime(new Date());
				baseCodeTypeService.update(baseCodeEntity);
			}
		}
	}

	@Override
	public ProjectsPmoResDto propertyFormsInvalid(HashMap<String, Object> map) {
		ProjectsPmoResDto res = new ProjectsPmoResDto();
		try {
			if (map != null && map.size() > 0) {
				for (Map.Entry<String, Object> entry : map.entrySet()) {
					BaseCodeValueDto queryDto = new BaseCodeValueDto();
					queryDto.setCodeValue(entry.getKey());
					queryDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					List<BaseCodeValue> baseCode = service.selectListByDto(queryDto);
					if (baseCode != null && baseCode.size() > 0) {
						BaseCodeValue codeEntity = baseCode.get(0);

						Date expiredTime = DateUtils.StringToDate(entry.getValue().toString());
						if (expiredTime == null) {
							throw new BusinessException("00000006", "日期转换错误");
						}
						BaseCodeValueDto updDto = new BaseCodeValueDto();
						codeEntity.setExpiredTime(expiredTime);
						BeanUtil.convert2T(updDto, codeEntity);
						service.update(updDto);
					} else {
						res.setCode("10000005");
						res.setDesc("只能是叶子节点");
						return res;
					}
				}
			} else {
				res.setCode("10000002");
				res.setDesc("没有参数值");
				return res;
			}
			res.setCode("00000000");
			res.setDesc("调用成功");
			return res;
		} catch (BusinessException e) {
			res.setCode("00000006");
			res.setDesc("日期转换错误");
		} catch (Exception e) {
			res.setCode("00000005");
			res.setDesc("数据库操作异常");
			logger.error("数据库操作异常: ", e);
		}
		return res;
	}

	@Override
	public Response<BaseCodeValue> lastUpdateTime(BaseCodeValueDto entity) {
		Response<BaseCodeValue> response = new Response<BaseCodeValue>();
		try {
			if (null == entity) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("dto查询"));
				return response;
			}
			BaseCodeValue bcv = service.lastUpdateTime(entity);
			if (null == bcv) {
				response.fail("90001", "查询数据失败");
			} else {
				response.success(bcv);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<BaseCodeValueInfo> getOptionRatio(BaseCodeValueInfo entity, String num) {
		ResponseList<BaseCodeValueInfo> response = new ResponseList<BaseCodeValueInfo>();
		try {
			if (null == entity) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("dto查询"));
				return response;
			}
			List<BaseCodeValueInfo> list = service.getOptionRatio(entity);
			if (null == list) {
				response.fail("90001", "查询数据失败");
			}
			// 将num转换为BigDecimal
			BigDecimal cusNum = new BigDecimal(num);
			// 设置百分比
			BigDecimal ro = new BigDecimal("100");
			// 格式化答题率
			DecimalFormat decimalFormat = new DecimalFormat("#.#");
			for (BaseCodeValueInfo info : list) {
				info.setRatio(decimalFormat.format(getRatio(ro, cusNum, info.getNum())));
			}
			response.success(list);
			;
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<BaseCodeValueInfo> getOptionRatioByEnum(BaseCodeValueInfo entity, String num, String codeName) {
		ResponseList<BaseCodeValueInfo> response = new ResponseList<BaseCodeValueInfo>();
		try {
			if (null == entity) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("dto查询"));
				return response;
			}
			List<BaseCodeValueInfo> list = service.getOptionRatioByEnum(entity);
			if (null == list) {
				response.fail("90001", "查询数据失败");
			}
			// 将num转换为BigDecimal
			BigDecimal cusNum = new BigDecimal(num);
			// 设置百分比
			BigDecimal ro = new BigDecimal("100");
			// 格式化答题率
			DecimalFormat decimalFormat = new DecimalFormat("#.#");
			Map<String, String> map = new HashMap<String, String>();
			for (BaseCodeValueInfo info : list) {
				map.put(info.getCodeName(), decimalFormat.format(getRatio(ro, cusNum, info.getNum())));
			}
			List<BaseCodeValueInfo> resList = new ArrayList<BaseCodeValueInfo>();
			// 获取对应的枚举Map
			Map enumMap = getMapByEnum(codeName);
			for (Iterator iter = enumMap.keySet().iterator(); iter.hasNext();) {
				String key = (String) iter.next();
				String value = (String) enumMap.get(key);
				BaseCodeValueInfo info = new BaseCodeValueInfo();
				// 保存参数名称
				info.setCodeName(value);
				// 保存比例，如没有改选项，则默认为0
				if (map.get(key) != null) {
					info.setRatio(map.get(key));
				} else {
					info.setRatio("0");
				}
				resList.add(info);
			}

			response.success(resList);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<BaseCodeValueInfo> getDocumentTypeRatio(BaseCodeValueInfo entity, String num) {
		ResponseList<BaseCodeValueInfo> response = new ResponseList<BaseCodeValueInfo>();
		try {
			if (null == entity) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("dto查询"));
				return response;
			}
			List<BaseCodeValueInfo> list = service.getDocumentTypeRatio(entity);
			if (null == list) {
				response.fail("90001", "查询数据失败");
			}
			// 将全部答题人转换成BigDecimal
			BigDecimal allNum = new BigDecimal(num);
			// 设置百分比
			BigDecimal ro = new BigDecimal("100");
			// 格式化答题率
			DecimalFormat decimalFormat = new DecimalFormat("#.#");
			// 获取全部选择人数
			BigDecimal cusNum = new BigDecimal("0");
			for (BaseCodeValueInfo info : list) {
				cusNum = cusNum.add(info.getNum());
			}
			// 计算单项选择率
			for (BaseCodeValueInfo info : list) {
				info.setRatio(decimalFormat.format(getRatio(ro, cusNum, info.getNum())));
			}
			// 计算家庭成员证件类型答题率
			BaseCodeValueInfo bcv = new BaseCodeValueInfo();
			bcv.setRatio(decimalFormat.format(getRatio(ro, allNum, cusNum)));
			bcv.setCodeName("title");
			list.add(bcv);

			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public String getBcvJsonArray(BaseCodeValueDto bcvDto) {
		JSONArray array = new JSONArray();
		ResponseList<BaseCodeValueDto> resList = findListByTypeName(bcvDto);
		List<BaseCodeValueDto> bcvList = resList.getEntity();
		for (BaseCodeValueDto bcv : bcvList) {
			JSONObject row = new JSONObject();
			row.put("value", bcv.getId());
			row.put("name", bcv.getCodeName());
			array.add(row);
		}
		//Response<JSONArray> returnArray = new Response<>();
		//returnArray.setEntity(JSONArray.toJSONString(array));
		return JSONArray.toJSONString(array);
	}

	/**
	 * 计算答题率
	 * 
	 * @param ro
	 *            百分比默认100
	 * @param cusNum
	 *            回答的人数
	 * @param num
	 *            选项选择数
	 * @return
	 */
	private BigDecimal getRatio(BigDecimal ro, BigDecimal cusNum, BigDecimal num) {
		// 当答题数或选择数为0时，不进行计算
		BigDecimal n = new BigDecimal("0");
		if (cusNum.compareTo(n) == 0 || num.compareTo(n) == 0) {
			return n;
		}
		// 计算比例
		BigDecimal ratio = num.divide(cusNum, 5, BigDecimal.ROUND_HALF_UP).multiply(ro);
		return ratio;
	}

	/**
	 * 转换Enum为Map
	 * 
	 * @param codeName
	 *            对应字段
	 * @return
	 */
	private Map getMapByEnum(String codeName) {
		Map map = new HashMap();
		// 性别
		if ("customer_sex".equals(codeName)) {
			map = EnumUtil.toMap(CustomerSexEnum.class);
		}
		// 意向等级
		if ("intention_level".equals(codeName)) {
			map = EnumUtil.toMap(IntentionLevelEnum.class);
		}
		// 客户状态
		if ("customer_status".equals(codeName)) {
			map = EnumUtil.toMap(CustomerStatusEnum.class);
		}
		// 需求面积
		if ("rq_demand_area".equals(codeName)) {
			map = EnumUtil.toMap(RqDemandAreaEnum.class);
		}
		// 预算总价
		if ("rq_budget_sumprice".equals(codeName)) {
			map = EnumUtil.toMap(RqBudgetSumPriceEnum.class);
		}
		// 预算单价
		if ("rq_budget_price".equals(codeName)) {
			map = EnumUtil.toMap(RqBudgetPriceEnum.class);
		}
		// 付款方式
		if ("rq_payment_method".equals(codeName)) {
			map = EnumUtil.toMap(PaymentMethodEnum.class);
		}
		// 购买车位
		if ("buy_car".equals(codeName)) {
			map = EnumUtil.toMap(BuyCarEnum.class);
		}
		// 需求户型规格
		if ("xuqiuhuxing_type".equals(codeName)) {
			map = EnumUtil.toMap(XuQiuHuXingEnum.class);
		}
		// 户籍所在地
		if ("pe_domicile_place".equals(codeName)) {
			map = EnumUtil.toMap(HujiEnum.class);
		}
		// 家庭年收入
		if ("pe_household_income".equals(codeName)) {
			map = EnumUtil.toMap(PeHouseholdIncomeEnum.class);
		}
		// 是否本公司业主
		if ("is_yezhu".equals(codeName)) {
			map = EnumUtil.toMap(IsOwnerCompanyEnum.class);
		}
		// 是否有子女||是否与老人同住||是否员工
		if ("is_zinv".equals(codeName) || "is_laoren".equals(codeName) || "is_yuangong".equals(codeName)) {
			map = EnumUtil.toMap(IsEnum.class);
		}
		// 目前居住的面积
		if ("re_currently_area".equals(codeName)) {
			map = EnumUtil.toMap(ReCurrentlyAreaEnum.class);
		}
		// 工作日联系时间
		if ("co_contact_time".equals(codeName)) {
			map = EnumUtil.toMap(CoContactTimeEnum.class);
		}
		// 周末联系时间
		if ("co_contact_weekend".equals(codeName)) {
			map = EnumUtil.toMap(CoContactWeekendEnum.class);
		}
		return map;
	}

	public static void main(String[] args) {
		Map map = EnumUtil.toMap(BuyCarEnum.class);
		Map map1 = EnumUtil.toMap(BuyCarEnum.class, "getNo");
		Map map2 = EnumUtil.toMap(BuyCarEnum.class, "getDes");

		System.out.println(map);
		System.out.println(map1);
		System.out.println(map2);
	}
}
